﻿using System.Collections.Generic;
using System.Data.Entity;
using System.Threading.Tasks;
using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.AutoMapper;
using Abp.Domain.Repositories;
using Abp.Linq.Extensions;
using KDS.Mes.Mes.Factorys.Dtos;
using KDS.Mes.Dto;
using KDS.Mes.Authorization;
using System.Linq.Dynamic.Core;
using System.Linq;
using Abp.UI;

namespace KDS.Mes.Mes.Factorys
{
    /// <summary>
    /// 工厂信息服务实现
    /// </summary>
    [AbpAuthorize(AppPermissions.Pages_Basic_Factorys)]
    public class FactoryAppService : MesAppServiceBase, IFactoryAppService
    {
        private readonly IRepository<Factory, int> _factoryRepository;
        private readonly IFactoryListExcelExporter _factoryListExcelExporter;

        /// <summary>
        /// 构造方法
        /// </summary>
        public FactoryAppService(
            IRepository<Factory, int> factoryRepository,
            IFactoryListExcelExporter factoryListExcelExporter
  )
        {
            _factoryRepository = factoryRepository;
            _factoryListExcelExporter = factoryListExcelExporter;
        }

        #region 工厂信息管理

        public async Task<ListResultDto<FactoryListDto>> GetFactorys()
        {
            var factorys = await _factoryRepository
                .GetAllListAsync();

            return new ListResultDto<FactoryListDto>(factorys.MapTo<List<FactoryListDto>>());
        }

           public PagedResultDto<FactoryListDto> GetPagedFctorys(GetFactoryInput input)
        {
            //初步过滤
            var query = _factoryRepository.GetAll();
            //排序
            query = !string.IsNullOrEmpty(input.Sorting) ? query.OrderBy(x => x.Id) : query.OrderByDescending(t => t.CreationTime);
            //获取总数
            var tasksCount = query.Count();
            //默认的分页方式
            //var taskList = query.Skip(input.SkipCount).Take(input.MaxResultCount).ToList();
            //ABP提供了扩展方法PageBy分页方式
            var taskList = query.PageBy(input).ToList();
            return new PagedResultDto<FactoryListDto>(tasksCount, taskList.MapTo<List<FactoryListDto>>());
        }
        /// <summary>
        /// 根据查询条件获取工厂信息分页列表
        /// </summary>
        public async Task<PagedResultDto<FactoryListDto>> GetPagedFactorysAsync(GetFactoryInput input)
        {
            var query = _factoryRepository.GetAll();
            //TODO:根据传入的参数添加过滤条件

            var factoryCount = await query.CountAsync();

            var factorys = await query
            .OrderBy(input.Sorting)
            .PageBy(input)
            .ToListAsync();

            var factoryListDtos = factorys.MapTo<List<FactoryListDto>>();
            return new PagedResultDto<FactoryListDto>(
            factoryCount,
            factoryListDtos
            );
        }

        /// <summary>
        /// 通过Id获取工厂信息信息进行编辑或修改 
        /// </summary>
        public async Task<GetFactoryForEditOutput> GetFactoryForEditAsync(NullableIdDto<int> input)
        {
            var output = new GetFactoryForEditOutput();

            FactoryEditDto factoryEditDto;

            if (input.Id.HasValue)
            {
                var entity = await _factoryRepository.GetAsync(input.Id.Value);
                factoryEditDto = entity.MapTo<FactoryEditDto>();
            }
            else
            {
                factoryEditDto = new FactoryEditDto();
            }

            output.Factory = factoryEditDto;
            return output;
        }


        /// <summary>
        /// 通过指定id获取工厂信息ListDto信息
        /// </summary>
        public async Task<FactoryListDto> GetFactoryByIdAsync(EntityDto<int> input)
        {
            var entity = await _factoryRepository.GetAsync(input.Id);

            return entity.MapTo<FactoryListDto>();
        }







        /// <summary>
        /// 新增或更改工厂信息
        /// </summary>
        public async Task CreateOrUpdateFactoryAsync(CreateOrUpdateFactoryInput input)
        {
            if (input.FactoryEditDto.Id.HasValue)
            {
                await UpdateFactoryAsync(input.FactoryEditDto);
            }
            else
            {
                await CreateFactoryAsync(input.FactoryEditDto);
            }
        }

        /// <summary>
        /// 新增工厂信息
        /// </summary>
        [AbpAuthorize(AppPermissions.Pages_Basic_Factorys_Create)]

        public virtual async Task<FactoryEditDto> CreateFactoryAsync(FactoryEditDto input)
        {
            //TODO:新增前的逻辑判断，是否允许新增
            await CheckFactoryIfAlreadyExists(input.FactoryName, input.FactoryCode, input.Id);
            var entity = input.MapTo<Factory>();

            entity = await _factoryRepository.InsertAsync(entity);
            return entity.MapTo<FactoryEditDto>();
        }

        /// <summary>
        /// 编辑工厂信息
        /// </summary>
        [AbpAuthorize(AppPermissions.Pages_Basic_Factorys_Edit)]
        public virtual async Task UpdateFactoryAsync(FactoryEditDto input)
        {
            //TODO:更新前的逻辑判断，是否允许更新
            await CheckFactoryIfAlreadyExists(input.FactoryName, input.FactoryCode, input.Id);
            var entity = await _factoryRepository.GetAsync(input.Id.Value);
            input.MapTo(entity);

            await _factoryRepository.UpdateAsync(entity);
        }

        /// <summary>
        /// 删除工厂信息
        /// </summary>
        [AbpAuthorize(AppPermissions.Pages_Basic_Factorys_Delete)]
        public async Task DeleteFactoryAsync(EntityDto<int> input)
        {
            //TODO:删除前的逻辑判断，是否允许删除
            await _factoryRepository.DeleteAsync(input.Id);
        }

        /// <summary>
        /// 批量删除工厂信息
        /// </summary>
        [AbpAuthorize(AppPermissions.Pages_Basic_Factorys_Delete)]
        public async Task BatchDeleteFactoryAsync(List<int> input)
        {
            //TODO:批量删除前的逻辑判断，是否允许删除
            await _factoryRepository.DeleteAsync(s => input.Contains(s.Id));
        }

        private async Task CheckFactoryIfAlreadyExists(string factoryName, string factoryCode, int? id = null)
        {
            var existingFactory = await _factoryRepository.GetAll()
                .FirstOrDefaultAsync(l => l.FactoryName == factoryName || l.FactoryCode == factoryCode);
            if (existingFactory == null)
            {
                return;
            }
            if (id != null && existingFactory.Id == id)
            {
                return;
            }
            throw new UserFriendlyException(L("ThisFactoryAlreadyExists"));
        }

        #endregion


        #region 工厂信息的Excel导出功能


        public async Task<FileDto> GetFactoryToExcel()
        {
            var entities = await _factoryRepository.GetAll().ToListAsync();

            var dtos = entities.MapTo<List<FactoryListDto>>();

            var fileDto = _factoryListExcelExporter.ExportFactoryToFile(dtos);



            return fileDto;
        }


        #endregion










    }
}
